import {
  emit
} from './eventBus.js'
import {
  dom,
  _append,
  _attr,
  _query,
  _closest,
  _toggleClassName,
  _style
} from './dom.js'
import { changeProperty } from '../utils/index.js'
import { _input, _number, _checkbox } from './input.js'
import { _select } from './select.js'
import { _popover } from './popover.js'
import { groupBy } from '../math/array.js'

const _formBtns = (fields, form, op) => {
  let btns = dom.div(op.map(t => dom.div(t.text, {
    class: `form-btn${t.className ? ' ' + t.className : ''} ${t.popover ? ' popover' : ''}`,
    type: 'button'
  }, {
    click: (e) => {
      let model = {}
      fields.filter(t => t.field).forEach(t => { //['text','number','select'].includes(t.type)
        let key = t.field
        let item = _query(`[name=${key}]`, form)
        let type = _attr(item, "type")
        switch (type) {
          case 'number':
            model[key] = Number(item.value)
            break;
          case 'checkbox':
            model[key] = item.checked
            break
          default:

            model[key] = item.value
        }
        // model[key] = type === 'number' ? Number(item.value) : item.value
      })
      let scope = {
        model,
        form,
        emit //事件
      }
      // 弹窗
      if (t.popover) {
        document.body.appendChild(_popover(t.popover, e.target))
      }


      t.click.call(scope, e, scope)
    }
  })), {
    class: 'form-btn-group'
  })
  return btns
}
// 表单
export const _form = (options = {}, events = {}) => {
  let form = dom.form([], {}, events)
  let {
    title,
    fields = [],
    op = [],
    // config
  } = options
  let formTitle = dom.div(title, {
    class: 'form-title'
  })

  let formBody
  // 分组
  if (fields.some(t => t.group)) {
    let group = groupBy(fields, (t => {
      return t.group || 'none'
    }))

    let formItemsGroup =
      Object.keys(group).map(key => {
        let fields = group[key]
        let formItems = fields.filter(t => t.field).map(field => _formItem(field, options))
        let itcon = dom.i('', {
          class: 'icon-arrow'
        })
        let groupTitle = dom.div([key, itcon], {
          class: 'form-item-group__title'
        }, (e) => {
          let el = e.target
          let groupContainer = _closest(el, '.form-item-group')
          if (groupContainer) {

            _toggleClassName(groupContainer, 'active')
            // let groupBody = _query('.form-item-group__body', groupContainer)
            // _toggleClassName(groupContainer, 'active', '',
            //   () => {

            //     _style(groupBody, {
            //       'height': '500px',
            //       overflow: 'hidden'
            //     })
            //     groupContainer.scrollIntoView()
            //   },
            //   () => {
            //     _style(groupBody, {
            //       'height': '0',
            //       overflow: 'hidden'
            //     })
            //   })
            groupContainer.scrollIntoView()
          }

        })
        let groupBody = dom.div(formItems, {
          class: 'form-item-group__body'
        })
        return dom.div(key === 'none' ? formItems : [groupTitle, groupBody], {
          class: `form-item-group ${key}`
        })

      })

    formBody = dom.div([formItemsGroup], {
      class: 'form-body'
    })
  } else {

    let formItems = fields.filter(t => t.field).map(field => _formItem(field, options))
    formBody = dom.div([formItems], {
      class: 'form-body'
    })
  }

  //

  let btns = _formBtns(fields, form, op)

  return _append(form, [formTitle, formBody, btns])
}

export const _formItem = (field, config = {}) => {
  let { type, value } = field
  // 改下属性名
  field = changeProperty(field, 'field', 'name')
  let style = config.labelWidth ? {
    width: config.labelWidth + 'px'
  } : null
  let itemLabel = dom.div(field.label, {
    class: 'form-item-label',
    title: field.label,
    style

  })
  let item = dom.div(itemLabel, {
    class: 'form-item',
    width: config.width
  })

  switch (type) {
    case "select": {
      let select = _select(value, {
        ...field,
        class: 'form-item-' + type,
        width: config.inputWidth,
        options: field.options
      })
      _append(item, select)
    }
      break
    case 'number':
    case "random":
      {
        let inputNumber = _number(value, {
          ...field,
          width: config.inputWidth,
          class: 'form-item-' + type
        })
        _append(item, inputNumber)
      }

      break;
    case 'boolean':
    case 'checkbox':
      {
        let checkbox = _checkbox(value, {
          ...field,
          class: 'form-item-' + type
        })
        let itemBody = dom.div(checkbox, {
          class: 'form-item-body'
        })
        _append(item, itemBody)
      }

      break;
    default:
      {
        let input = _input(value, {
          ...field,
          width: config.inputWidth,
          class: 'form-item-input'
        })
        _append(item, input)
      }

  }
  return item
}
